import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 工具类，封装数据库操作
 */
public class JDBCUtil {
    /**
     * 建立数据库连接
     * 
     * @return 返回一个connection对象
     * @throws Exception
     */
    public Connection gitConn() throws Exception {
        Connection con = null;
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/jdbctest?zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai";
        con = DriverManager.getConnection(url, "root", "root");
        return con;
    }

    /**
     * 关闭数据库链接
     * 
     * @param con
     * @throws Exception
     */
    public void closeConn(Connection con) throws Exception {
        if (con != null) {
            con.close();
        }
        con = null;
    }

    /**
     * 解析结果集，返回一个list<User>
     * @param rs
     * @return
     * @throws Exception
     */
    public List<User> rs2List(ResultSet rs) throws Exception {
        List<User> list = new ArrayList<>();
        
        while (rs.next()) {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setUserName(rs.getString("username"));
            user.setPassWord(rs.getString("password"));
            user.setAge(rs.getInt("age"));
            list.add(user);
        }
        return list;
    }

    /**
     * 遍历list集合
     */
    public void printList(List<User> list){
        for (User user : list) {
            System.out.println(user);
        }
    }
}
